const fs = require("fs");

function getSectionsSchema(path) {
    const content = fs.readFileSync(path, "utf-8");
    if (content) {
        const schemaRegExpStr = /{% schema %}([\s\S]*?){% endschema %}/g;
        const schemBody = content.match(schemaRegExpStr);
        if (schemBody) {
            return JSON.parse(schemBody[0].replace(/({% schema %})|({% endschema %})/g, ""));
        }
    }
    return "";
}

let DefaultBlocksSetting = {};

function getDefaultSectionsSchema() {
    const dir = `./src/theme/default/sections`;
    const filenames = fs.readdirSync(dir);
    filenames.forEach(function (file) {
        DefaultBlocksSetting[file.split(".")[0]] = getSectionsSchema(dir + "/" + file);
    });
    return DefaultBlocksSetting;
}

function getAllSectionsSchema(template) {
    const dir = `./src/theme/${template}/sections`;
    const filenames = fs.readdirSync(dir);
    let blocksSetting = getDefaultSectionsSchema();
    filenames.forEach(function (file) {
        blocksSetting[file.split(".")[0]] = getSectionsSchema(dir + "/" + file);
    });
    return blocksSetting;
}

module.exports = { getAllSectionsSchema, getSectionsSchema };
